package com.qs.eggs.view.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.Zxing.Demo.CaptureActivity;
import com.lzy.okgo.callback.StringCallback;
import com.qs.eggs.Constants;
import com.qs.eggs.R;
import com.qs.eggs.account.LoginActivity;
import com.qs.eggs.adapter.BaseAdapter;
import com.qs.eggs.adapter.CategoryFirstMenuAdapter;
import com.qs.eggs.adapter.CategorySecondmenuAdapter;
import com.qs.eggs.api.HttpApi;
import com.qs.eggs.base.fragment.BaseFragment;
import com.qs.eggs.bean.Fenlei_item;
import com.qs.eggs.bean.Fenlei_items;
import com.qs.eggs.bean.GridViewItem;
import com.qs.eggs.view.activity.SortActivity;
import com.qs.eggs.view.prodetail.activity.ProDetailActivity;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 商品分类页，分左右两级展示商品，第一级是商品类型，第二级是详细的商品.
 */
public class CategoryFragment extends BaseFragment {
    public static GridView mGridView;
    private static RecyclerView mRecyclerView;
    private EditText mSearch;
    private TextView icSearch;
    public static ArrayList<Fenlei_item> arrtotol = new ArrayList<Fenlei_item>();
    public static CategoryFirstMenuAdapter adapterFirst;
    public static CategorySecondmenuAdapter adaptertwo;
    public static String firstId;

    public static String proid;

    private ImageView mScanner;
    public static CategoryFragment instance;
    public static String flag="";
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_category;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        instance=this;
        mGridView = instance.findView(R.id.main_gridview);
        mSearch = findView(R.id.poi_et_search);
        icSearch=findView(R.id.img_search);
        mScanner=findView(R.id.erweima);
        mScanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpApi.cheakIsLogin(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if(s.equals("\"true\"")){
//                            Intent intent = new Intent(getContext(), CaptureActivity.class);
//                            startActivityForResult(intent, REQUEST_CODE);
                            Intent intent = new Intent(getActivity(), CaptureActivity.class);
                            startActivity(intent);
                        }else {
                            LoginActivity.show(getContext());
                        }
                    }
                });
            }
        });
        icSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mSearch.getText().length()==0){
                    Toast.makeText(getContext(),"请输入搜索内容",Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent sort=new Intent(getActivity(),SortActivity.class);
                sort.putExtra("biaoshi","search");
                sort.putExtra("pronameLIKE",mSearch.getText().toString().trim());
                startActivity(sort);
            }
        });
    }

    public static void fromPrimary(final int positionFromPrimary){

        HttpApi.FirstCategoryList(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                final ArrayList<Fenlei_item> arrarytotol = new ArrayList<Fenlei_item>();

                JSONArray jsonArr = null;
                try {
                    jsonArr = new JSONArray(s);
                    for (int i = 0; i < jsonArr.length(); i++) {
                        HashMap<String, String> idMap = new HashMap<String, String>();

                        String name = jsonArr.getJSONObject(i)
                                .getString("name");
                        firstId = jsonArr.getJSONObject(i)
                                .getString("id");
                        Fenlei_item item = new Fenlei_item(name, firstId);
                        arrarytotol.add(item);
                    }

                    final CategoryFirstMenuAdapter adapterFirst;
                    adapterFirst = new CategoryFirstMenuAdapter(instance.getContext(), arrarytotol);
                    mGridView.setAdapter(adapterFirst);
                    adapterFirst.setSeclect(positionFromPrimary);
                    adapterFirst.notifyDataSetChanged();

                    getSecondPro(arrarytotol.get(positionFromPrimary).getProid());

                    instance.initData();
                    mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @SuppressLint("NewApi")
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                                final int position, long id) {
                            // TODO Auto-generated method stub

                            adapterFirst.setSeclect(position);
                            adapterFirst.notifyDataSetChanged();

                            getSecondPro(arrarytotol.get(position).getProid());

                        }
                    });


                } catch (JSONException e) {
                    // TODO Auto-generated catch bloc
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        if(!flag.equals("1")){
            HttpApi.FirstCategoryList(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    final ArrayList<Fenlei_item> arrarytotol = new ArrayList<Fenlei_item>();

                    JSONArray jsonArr = null;
                    try {
                        jsonArr = new JSONArray(s);
                        for (int i = 0; i < jsonArr.length(); i++) {
                            HashMap<String, String> idMap = new HashMap<String, String>();

                            String name = jsonArr.getJSONObject(i)
                                    .getString("name");
                            firstId = jsonArr.getJSONObject(i)
                                    .getString("id");
                            Fenlei_item item = new Fenlei_item(name, firstId);
                            arrarytotol.add(item);
                        }
                        setmGridViewFirst(arrarytotol);
                        //初始化二级列表
                        getSecondPro(arrtotol.get(0).getProid());

                    } catch (JSONException e) {
                        // TODO Auto-generated catch bloc
                    }
                }
            });
        }

    }

    /**
     * FirstGridView
     */
    public static void setmGridViewFirst(final ArrayList<Fenlei_item> arrarytotol) {

        arrtotol = arrarytotol;

        adapterFirst = new CategoryFirstMenuAdapter(instance.getContext(), arrarytotol);
        mGridView.setAdapter(adapterFirst);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    final int position, long id) {
                // TODO Auto-generated method stub

                adapterFirst.setSeclect(position);
                adapterFirst.notifyDataSetChanged();

                getSecondPro(arrtotol.get(position).getProid());

            }
        });

    }
    /**
     * SecondMeun
     */
    public static void setmRecyclerView(final ArrayList<Fenlei_items> arraryTwo) {

        mRecyclerView =instance.findView(R.id.recyclerview);
        if (arraryTwo.size()>0){
           // arrarytwo = arraryTwo.get(0);
        }else {

        }
        adaptertwo = new CategorySecondmenuAdapter(instance.getContext(), arraryTwo);
        adaptertwo.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent=new Intent(instance.getActivity(),ProDetailActivity.class);
                intent.putExtra("proid",arraryTwo.get(position).getProid());
                intent.putExtra("type",arraryTwo.get(position).getType());
                instance.startActivity(intent);

            }
        });
        mRecyclerView.setAdapter(adaptertwo);
        mRecyclerView.setLayoutManager(new GridLayoutManager(instance.getContext(), 3));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    /**
     * 二级商品列表的获取
     */

    public static void setPosition(){

        mGridView.setSelection(2);
    }
    public static void getSecondPro(String proid){
        HttpApi.SecondCategoryList(proid,new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                final ArrayList<Fenlei_items> arrarytotol = new ArrayList<Fenlei_items>();

                JSONArray jsonArr = null;
                try {
                    jsonArr = new JSONArray(s);
                    ArrayList<HashMap<String, String>> idList = new ArrayList<>();
                    for (int i = 0; i < jsonArr.length(); i++) {
                        HashMap<String, String> idMap = new HashMap<String, String>();

                        String name = jsonArr.getJSONObject(i)
                                .getString("proname");
                        String proid = jsonArr.getJSONObject(i)
                                .getString("id");
                        String type = jsonArr.getJSONObject(i)
                                .getString("type");
                        String img = Constants.URL_BASE+"productimages/"+ jsonArr.getJSONObject(i)
                                .getString("autoname");
                        idList.add(idMap);
                        Fenlei_items item = new Fenlei_items(img, name,proid,name,name,type);
                        arrarytotol.add(item);
                    }
                    setmRecyclerView(arrarytotol);

                } catch (JSONException e) {
                    // TODO Auto-generated catch bloc
                }
            }
        });
    }

}
